package com.wu.neihan.service;

import java.math.BigInteger;
import java.util.List;

import org.apache.log4j.Logger;

import com.wu.neihan.model.Gather;
import com.wu.util.ConMysql;
import com.wu.util.DateUtil;
import com.wu.util.HttpUtil;
import com.wu.util.JsonUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class QueueProduce extends Thread {
	private static Logger logger = Logger.getLogger(QueueProduce.class);
	private ConMysql conMysql = new ConMysql();
	@Override
	public void run() {

		while (true) {
			try {
				if (QueueService.checkSize(500)) {
					sleep(3000 * 1);
				} else {
					producesMain();
				}
			} catch (Exception e) {
				e.printStackTrace();
				logger.info("致命错误");
			}
		}

	}
	
	public  void producesMain(){
		List<Gather> gatherList = null;
		try {
//			gatherList = ConMysql.selectSql("select * from mto_gather where type=1 order by last_date  limit 300");
//			for(int i=0;i<gatherList.size();i++){
//				String id=gatherList.get(i).getStartId();
//				QueueService.putUserQueue(id); 
//				ConMysql.insertSql("update mto_gather set states=1 where id='"+gatherList.get(i).getId()+"'");
//			}
			gatherList = conMysql.selectSql("select * from mto_gather where type=2 and states=0 order by last_date  limit 300");
			for(int i=0;i<gatherList.size();i++){
				String id=gatherList.get(i).getStartId();
				QueueService.putpostQueue(id); 
				conMysql.insertSql("update mto_gather set states=1 where id='"+gatherList.get(i).getId()+"'");
			}
//			gatherList = ConMysql.selectSql("select * from mto_gather where type=3 order by last_date  limit 300");
//			for(int i=0;i<gatherList.size();i++){
//				String id=gatherList.get(i).getStartId();
//				QueueService.putcommentQueue(id); 
//				ConMysql.insertSql("update mto_gather set states=1 where id='"+gatherList.get(i).getId()+"'");
//			}
			if (!QueueService.checkSize(100)) {
				producesInfo();
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("主要生产者从数据库获取数据失败");
		}
	}
	
	//采集推荐列表信息段子内容直接入库
	// 采集投稿信息
		public  void caiPostsInfo() {

			// 获取采集链接
			String url = "http://is.snssdk.com/neihan/stream/mix/v1/";

			// 读取内容封装
			String body = HttpUtil.sendGet(url);
			JSONObject bodyJs = JsonUtil.stringToJson(JsonUtil.stringToJson(body).getString("data"));
			if (bodyJs.size() > 1) {
				JSONArray bodyJa = JsonUtil.stringToJsonArry(bodyJs.getString("data"));
				for (int i = 0; i < bodyJa.size(); i++) {

					JSONObject bodyTemp;
					bodyTemp = JsonUtil.stringToJson(JsonUtil.stringToJson(bodyJa.get(i).toString()).getString("group"));

					// 通用内容采集
					String group = "1";
					String id = bodyTemp.getString("user_id");
					String biaoqian = bodyTemp.getString("category_name");
					String idstr = bodyTemp.getString("id");
					String statusDesc = bodyTemp.getString("status_desc");
					String text = bodyTemp.getString("text");
					String content = bodyTemp.getString("content");
					int digg = bodyTemp.getInt("digg_count");
					int bury = bodyTemp.getInt("bury_count");
					int share = bodyTemp.getInt("share_count");
					int comment = bodyTemp.getInt("comment_count");
					String imageUrl = "";
					String videoImgUrl = "";
					String videoUrl = "";
					String width = "";
					String height = "";
					String privacy = "0";// 是否私密，后面将改为是否匿名
					// System.out.println(bodyTemp.toString());
					if (bodyTemp.getBoolean("is_anonymous")) {
						privacy = "1";
					}
					// System.out.println(biaoqian);
					// 图片采集
					// 大图格式例子
					// url=http://p3.pstatp.com/w540/11aa00031c961e2e8d0f.webp
					// url=http://pb2.pstatp.com/w540/11aa00031c961e2e8d0f.webp
					// url=http://pb3.pstatp.com/w540/11aa00031c961e2e8d0f.webp
					// 小图格式例子
					// url=http://p3.pstatp.com/w480/11aa00031c961e2e8d0f.webp
					// url=http://pb2.pstatp.com/w480/11aa00031c961e2e8d0f.webp
					// url=http://pb3.pstatp.com/w480/11aa00031c961e2e8d0f.webp
					if (bodyTemp.containsKey("large_image")) {
						JSONObject videoJson = JsonUtil.stringToJson(bodyTemp.getString("large_image"));
						group = "2";
						imageUrl = JsonUtil
								.stringToJson(JsonUtil.stringToJsonArry(videoJson.getString("url_list")).get(0).toString())
								.getString("url");
						width = videoJson.getString("r_width");
						// System.out.println(width);
						height = videoJson.getString("r_height");
						// System.out.println(imageUrl);
					}

					// 视频采集
					// 缩略图
					if (bodyTemp.containsKey("large_cover")) {
						videoImgUrl = JsonUtil.stringToJson(JsonUtil
								.stringToJsonArry(
										JsonUtil.stringToJson(bodyTemp.getString("large_cover")).getString("url_list"))
								.get(0).toString()).getString("url");
						// System.out.println(videoImgUrl);
					}
					// 视频链接
					// http://ic.snssdk.com/neihan/video/playback/?video_id=47bd2bb976fe470090373dbcae8151fa&quality=origin&line=0&is_gif=0
					// http://ic.snssdk.com/neihan/video/playback/?video_id=47bd2bb976fe470090373dbcae8151fa&quality=720p&line=0&is_gif=0
					// http://ic.snssdk.com/neihan/video/playback/?video_id=47bd2bb976fe470090373dbcae8151fa&quality=480p&line=0&is_gif=0
					// http://ic.snssdk.com/neihan/video/playback/?video_id=47bd2bb976fe470090373dbcae8151fa&quality=360p&line=0&is_gif=0
					if (bodyTemp.containsKey("origin_video")) {
						group = "3";
						JSONObject videoJson = JsonUtil.stringToJson(bodyTemp.getString("origin_video"));
						videoUrl = JsonUtil
								.stringToJson(JsonUtil.stringToJsonArry(videoJson.getString("url_list")).get(0).toString())
								.getString("url");
						// System.out.println(videoUrl);
						width = videoJson.getString("width");
						// System.out.println(width);
						height = videoJson.getString("height");
						// System.out.println(height);
					}

					String contentBody = content;
					// 存储采集
					if (!imageUrl.equals("")) {
						contentBody = "<img  src=" + imageUrl + "  width=" + width + " height=" + height + " />";
						// contentBody= "<iframe src=/getRes?url=" + imageUrl +
						// "
						// frameborder=0 scrolling=no width=" + width
						// + " height=" + height + " marginheight=0
						// marginwidth=0
						// ></iframe>";
					}
					if (!conMysql.checkId("select id from mto_posts where id='" + idstr + "' limit 1")) {
						String sql = "INSERT INTO `mto_posts` VALUES ('" + idstr + "', '" + id + "', " + comment + ", '"
								+ contentBody + "', '" + DateUtil.getDate(bodyTemp.getInt("create_time") + "000", null)
								+ "', 'ueditor', '0', '0', '" + group + "', '0', '0', null, '" + privacy + "', '0', '"
								+ content + "', '" + biaoqian + "', '" + text + "', '8', '" + bury + "', '" + digg + "', '"
								+ share + "');";

						// System.out.println(sql);
						try {
							if (conMysql.insertSql(sql) == 1) {
								
								logger.info("插入段子成功：" + text);
								// GatherService.saveGather("插入段子成功：" + content, 3);

								if (!videoUrl.equals("")) {
									sql = " INSERT INTO `mto_posts_attribute` VALUES ('" + idstr + "', '" + videoImgUrl
											+ "', '" + videoUrl + "','" + height + "','" + width + "');";

									// System.out.println(sql);
									try {
										if (conMysql.insertSql(sql) == 1) {
											logger.info("插入附件成功：" + content);
											// 放入带采集的评论队列库表
											QueueService.putcommentQueue(idstr);
											// GatherService.saveGather("插入附件成功：" +
											// content, 3);
										} else {
											logger.info("插入附件失败：" + content);
											// GatherService.saveGather("插入附件失败：" +
											// content, 3);
										}
									} catch (Exception e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
										logger.info("插入附件失败：" + content);
									}
								}

							} else {
								logger.info("插入段子失败：" + text);
								// GatherService.saveGather("插入段子失败：" + content, 3);
							}
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							logger.info("插入段子失败：" + text);
						}
					}
				}
			} else {
				logger.info("列表信息错误！");
				// GatherService.saveGather("段子信息不纯在：" + id, 3);
			}

		}
		
	
	// 采集推荐列表信息  还采集ID
	public static void producesInfo() {
		// 获取采集链接
		String url = "http://is.snssdk.com/neihan/stream/mix/v1/";

		// 读取内容封装
		String body = HttpUtil.sendGet(url);
		String userInfo = "";
		JSONObject bodyJs = JsonUtil.stringToJson(JsonUtil.stringToJson(body).getString("data"));
		logger.info("主要生产者获取新消息：" + bodyJs.size());
		if (bodyJs.size() > 1) {
			JSONArray bodyJa = JsonUtil.stringToJsonArry(bodyJs.getString("data"));
			for (int i = 0; i < bodyJa.size(); i++) {

				try {
					JSONObject bodyTemp;
					bodyTemp = JsonUtil
							.stringToJson(JsonUtil.stringToJson(bodyJa.get(i).toString()).getString("group"));

					// 采集内容
					String postid = bodyTemp.getString("group_id");
					String userid = JsonUtil.stringToJson(bodyTemp.getString("user")).getString("user_id");
					//QueueService.putUserQueue(userid);
					QueueService.putpostQueue(userid);
					//QueueService.putcommentQueue(postid);
					//userInfo = "主要生产者添加用户到采集队列ID为：" + userid ;
					//logger.info(userInfo);
					userInfo="";
					userInfo = "主要生产者添加段子到采集队列ID为：" + postid ;
					logger.info(userInfo);
					userInfo="";
//					if (String.valueOf(i).endsWith("5")) {
//						GatherService.saveGather(userInfo, 5);
//						userInfo = "";
//					}
				} catch (Exception e) {
					userInfo = "主要生产者添加生产队列出错！！<br/>";
					logger.info(userInfo);
					e.printStackTrace();
				}
			}
		} else {
			logger.info("获取首页信息错误！！！");
			//GatherService.saveGather("获取首页信息错误！！！", 5);
		}
	}
}
